<template>
  <div class="flexContent">
    <div class="top">
      <h3 style="margin-bottom: 30px;">订单信息</h3>
      <div class="rows" style="margin-bottom: 15px;">
        <span class="col">预充值余额：{{ balance }} 元</span>
        <span class="col">订货总额（元）：{{ totalMoney }}元</span>
      </div>
      <div class="rows" v-if="remark">
        <span class="col">拒绝原因：{{ remark }}</span>
      </div>
    </div>
    <div class="table">
      <el-form :model="form" ref="form" :rules="rules" :inline="false" @submit.native.prevent>
        <el-table border class="tablebox" :max-height="600" :data="form.tableData" show-summary
          :summary-method="getSummaries" size="medium">
          <el-table-column label="序号" type="index" align="center" width="80" />
          <el-table-column align="center" label="商品名称" prop="name" />
          <el-table-column align="center" label="单价（元/KG）" prop="outboundPrice" />
          <el-table-column align="center" label="单位" prop="unit">
            <template v-slot="{ row }">
              <span>
                {{ row.unit == 0 ? 'KG' : '数量' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="配送规格" prop="deliveryNorms" />
          <el-table-column align="center" label="数量" prop="deliveryCount" />
          <el-table-column align="center" label="重量" prop="buyCount" min-width="180">
            <template v-slot="scope">
              <div>
                <el-form-item :prop="'tableData.' +
                  scope.$index +
                  '.buyCount'
                  " :rules="rules.buyCount" v-if="isDetail != '0'">
                  <el-input v-clearEmoji v-model="scope.row.buyCount" placeholder="请输入重量" size="small"></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.buyCount }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="采购价（元）" prop="pickMoney" />
        </el-table>
      </el-form>
    </div>
    <div class="returnBtn">
      <el-button class="addBtn" @click="toExamine(1)" v-if="isDetail == '1'">审核通过</el-button>
      <el-button class="delBtn" @click="showDia" v-if="isDetail == '1'">审核拒绝</el-button>
      <el-button class="celBtn" @click="returnList">返回</el-button>
    </div>
    <el-dialog title="审核拒绝" :visible.sync="dialogVisible" width="30%">
      <el-input v-clearEmoji type="textarea" :rows="5" placeholder="请输入拒绝原因" maxlength="100" v-model.trim="textarea"
        style="width: 100%;"></el-input>
      <span slot="footer">
        <el-button class="celBtn" @click="dialogVisible = false">取 消</el-button>
        <el-button class="addBtn" @click="toExamine(2)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { DecimalUtils } from '@/utils/math';
import { reqToExamine, reqGenericGoodsById } from '@/api/genericGoods';
export default {
  name: 'GoodsExamineDetail',
  data() {
    return {
      form: {
        tableData: []
      },
      balance: '',
      dialogVisible: false,
      totalMoney: '',
      textarea: '',
      id: '',
      isDetail: '',
      remark: '',
      rules: {
        buyCount: [
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,3})?$/,
            message: '重量只能是数字或小数',
            trigger: 'change'
          },
          {
            required: 'true',
            message: '重量不能为空',
            trigger: 'change'
          }
        ]
      }
    };
  },
  created() {
    this.id = this.$route.query.id ? this.$route.query.id : '';
    this.isDetail = this.$route.query.isDetail;
    console.log('this.$route.query.isDetail', this.$route.query.isDetail, this.isDetail);
    if (this.id) {
      this.getExamineDetail();
    }
  },
  methods: {
    returnList() {
      this.closeTag();
    },
    async getExamineDetail() {
      const res = await reqGenericGoodsById({ id: this.id });
      if (res.code === 200) {
        this.form.tableData = res.data.detailsList;
        this.balance = res.data.balance;
        this.totalMoney = res.data.totalMoney;
        this.remark = res.data.remark;
      }
    },
    async toExamine(state) {
      if (state === 1) {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const detailsList = this.form.tableData.map(item => {
              return {
                id: item.id,
                buyCount: item.buyCount
              };
            });
            if (state === 1 && this.totalMoney > this.balance) {
              this.$message.warning('余额不足');
              return;
            }
            const res = await reqToExamine({
              id: this.id,
              status: state,
              totalMoney: this.totalMoney,
              detailsList,
              remark: this.textarea
            });
            if (res.code === 200) {
              this.$message.success('审核成功');
              this.returnList();
            }
          } else {
            this.$message.warning('请检查输入信息')
            return false
          }
        })
      } else {
        if (!this.textarea) {
          this.$message.warning('请输入拒绝原因');
          return;
        } else {
          const res = await reqToExamine({
            id: this.id,
            status: state,
            remark: this.textarea
          });
          if (res.code === 200) {
            this.$message.success('审核成功');
            this.returnList();
          }
        }
      }




    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        data.forEach(item => {
          if (!isNaN(item.buyCount)) {
            item.pickMoney = DecimalUtils.multiply(
              item.buyCount,
              item.outboundPrice
            );
          } else {
            item.pickMoney = 0;
          }
        });
        const values = data.map(item => Number(item[column.property]));
        if (column.property === 'pickMoney') {
          if (this.isDetail == '0') {
            sums[index] = this.totalMoney;
            // 详情状态用后台数据回显
            // if (column.property === 'buyNumber') {

            // }
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return DecimalUtils.add(prev, value);
              } else {
                return prev;
              }
            }, 0);
            sums[index] = sums[index].toFixed(2);
            this.totalMoney = sums[index];
            // if (column.property === 'buyNumber') {
            // } else if(column.property === 'buyMoney'){
            //   this.totalPrice = sums[index]
            // }else {
            //   this.totalPiece = sums[index]
            // }
          }
        }
      });
      return sums;
    },
    showDia() {
      this.dialogVisible = true;
    }
  }
};
</script>

<style scoped lang="scss">
.flexContent {
  h3 {
    margin: 0;
    margin-bottom: 10px;
  }

  .top {
    .rows {
      display: flex;
      margin-bottom: 10px;

      .col {
        width: 50%;
      }
    }
  }
}
</style>
